﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using KC.DataAccess.MV6;
using KC.ExtensionMethods;

namespace KC.Business.Meta.Jobs
{
	public class SearchStatusUpdateJob : JobBase 
	{
		protected override void PreProcess_Global()
		{
		}
		protected override void Process_Global()
		{
			UpdateResults("Updated " + DoLookup().ToString() + " records",false);
		}
		protected override void PostProcess_Global()
		{
		}

		#region Implementation

		/// <summary>Looks up Google query positions for all tracked SearchStatus records</summary>
		/// <returns>Number of rows affected successfully</returns>
		protected int DoLookup()
		{
			int numErrors = 0,
				numUpdated = 0,
				num = dcMV6.SearchStatus.Count();
			foreach (SearchStatus ss in dcMV6.SearchStatus)
			{
				UpdateResults("On SearchStatus " + (numErrors + numUpdated + 1).ToString() + " of " + num.ToString(), true);
				if (numErrors > 10)
				{
					KC.Logging.Logger.Write("META", "Job failed", "Maximum number of errors reached, giving up", KC.Logging.Logger.Severity.Error);
					return numUpdated;
				}
				int status = -1;
				try
				{
					switch (ss.Engine)
					{
						case "google":
							status = FindGooglePosition(ss.Query);
							break;
						// TODO: Add more cases and FindPosition methods
					}
					numUpdated++;
				}
				catch (Exception ex)
				{
					numErrors++;
					KC.Logging.Logger.Write("META", ex, Logging.Logger.Severity.Warning);
					continue;
				}

				ss.Rank = status;
				ss.LastChecked = DateTime.Now;
			}
			dcMV6.SubmitChanges();
			return numUpdated;
		}

		/// <summary>Finds my current top rank on Google for a given term</summary>
		/// <param name="query">Query to Google</param>
		/// <returns>int representing the hit number on the Google search results</returns>
		protected static int FindGooglePosition(string query)
		{
			string GoogleUrl = @"http://www.google.com/search?hl=en&source=hp&aq=f&oq=&aqi=g10&start={0}&q={1}";
			string html = "";
			for (int CurPage=0; CurPage < 10; CurPage++) {
				using (WebClient wc = new WebClient())
					html = wc.DownloadString(string.Format(GoogleUrl, new string[] {CurPage.ToString(), HttpUtility.UrlEncode(query)} ));
				int HitsPerPage = 10;

				List<string> links = KC.Business.Net.Web.GetLinksFromHtml(html);
				List<string> links2 = new List<string>();
				foreach (string link in links)
					if (link.ToLower().Contains("class=l"))
						links2.Add(link);

				for (int i = 0; i < links2.Count; i++)
					if (new Uri(links2[i]).isMyDomain())
						return (CurPage * HitsPerPage) + i + 1;
			}
			return -1;
		}

		#endregion Implementation
	}
}
